import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import dayjs from 'dayjs'

export const useReminderStore = defineStore('reminder', () => {
  // 提醒列表
  const reminders = ref([])
  const isReminderVisible = ref(false)
  
  // 提醒类型
  const REMINDER_TYPES = {
    MATERIAL_MISSING: 'material_missing',     // 材料缺失
    MATERIAL_INCOMPLETE: 'material_incomplete', // 材料不完整
    MATERIAL_EXPIRED: 'material_expired',     // 材料过期
    DEADLINE_APPROACHING: 'deadline_approaching', // 截止日期临近
    REVIEW_PENDING: 'review_pending'          // 待审核
  }

  // 提醒优先级
  const PRIORITY_LEVELS = {
    LOW: 'low',
    MEDIUM: 'medium',
    HIGH: 'high',
    URGENT: 'urgent'
  }

  // 计算属性
  const activeReminders = computed(() => 
    reminders.value.filter(reminder => !reminder.dismissed && !reminder.resolved)
  )

  const unreadReminders = computed(() => 
    activeReminders.value.filter(reminder => !reminder.read)
  )

  const urgentReminders = computed(() => 
    activeReminders.value.filter(reminder => 
      reminder.priority === PRIORITY_LEVELS.URGENT || 
      reminder.priority === PRIORITY_LEVELS.HIGH
    )
  )

  const materialReminders = computed(() => 
    activeReminders.value.filter(reminder => 
      reminder.type === REMINDER_TYPES.MATERIAL_MISSING ||
      reminder.type === REMINDER_TYPES.MATERIAL_INCOMPLETE ||
      reminder.type === REMINDER_TYPES.MATERIAL_EXPIRED
    )
  )

  const reminderCount = computed(() => activeReminders.value.length)
  const unreadCount = computed(() => unreadReminders.value.length)

  // 添加提醒
  const addReminder = (reminderData) => {
    const reminder = {
      id: generateId(),
      type: reminderData.type,
      title: reminderData.title,
      message: reminderData.message,
      priority: reminderData.priority || PRIORITY_LEVELS.MEDIUM,
      caseId: reminderData.caseId,
      caseNumber: reminderData.caseNumber,
      clientName: reminderData.clientName,
      targetRole: reminderData.targetRole, // 目标角色：client, lawyer, etc.
      materialType: reminderData.materialType, // 材料类型
      materialId: reminderData.materialId,
      dueDate: reminderData.dueDate,
      createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      read: false,
      dismissed: false,
      resolved: false,
      actions: reminderData.actions || [], // 可执行的操作
      metadata: reminderData.metadata || {} // 额外的元数据
    }
    
    reminders.value.unshift(reminder)
    return reminder.id
  }

  // 批量添加提醒
  const addReminders = (reminderList) => {
    const ids = []
    reminderList.forEach(reminderData => {
      ids.push(addReminder(reminderData))
    })
    return ids
  }

  // 标记为已读
  const markAsRead = (reminderId) => {
    const reminder = reminders.value.find(r => r.id === reminderId)
    if (reminder) {
      reminder.read = true
    }
  }

  // 批量标记为已读
  const markAllAsRead = () => {
    reminders.value.forEach(reminder => {
      if (!reminder.dismissed && !reminder.resolved) {
        reminder.read = true
      }
    })
  }

  // 忽略提醒
  const dismissReminder = (reminderId) => {
    const reminder = reminders.value.find(r => r.id === reminderId)
    if (reminder) {
      reminder.dismissed = true
      reminder.read = true
    }
  }

  // 解决提醒（材料已补充）
  const resolveReminder = (reminderId, resolution) => {
    const reminder = reminders.value.find(r => r.id === reminderId)
    if (reminder) {
      reminder.resolved = true
      reminder.read = true
      reminder.resolvedAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
      reminder.resolution = resolution
    }
  }

  // 根据案件ID解决相关提醒
  const resolveCaseReminders = (caseId, materialType = null) => {
    reminders.value.forEach(reminder => {
      if (reminder.caseId === caseId && !reminder.resolved) {
        // 如果指定了材料类型，只解决该类型的提醒
        if (materialType && reminder.materialType !== materialType) {
          return
        }
        reminder.resolved = true
        reminder.read = true
        reminder.resolvedAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
        reminder.resolution = `材料已补充${materialType ? ` - ${materialType}` : ''}`
      }
    })
  }

  // 删除提醒
  const removeReminder = (reminderId) => {
    const index = reminders.value.findIndex(r => r.id === reminderId)
    if (index !== -1) {
      reminders.value.splice(index, 1)
    }
  }

  // 清理已解决的提醒
  const cleanupResolvedReminders = (daysOld = 7) => {
    const cutoffDate = dayjs().subtract(daysOld, 'day')
    reminders.value = reminders.value.filter(reminder => {
      if (reminder.resolved && reminder.resolvedAt) {
        return dayjs(reminder.resolvedAt).isAfter(cutoffDate)
      }
      return true
    })
  }

  // 获取特定类型的提醒
  const getRemindersByType = (type) => {
    return activeReminders.value.filter(reminder => reminder.type === type)
  }

  // 获取特定案件的提醒
  const getRemindersByCase = (caseId) => {
    return activeReminders.value.filter(reminder => reminder.caseId === caseId)
  }

  // 获取特定角色的提醒
  const getRemindersByRole = (role) => {
    return activeReminders.value.filter(reminder => 
      !reminder.targetRole || reminder.targetRole === role
    )
  }

  // 创建材料缺失提醒
  const createMaterialMissingReminder = (caseData, materialData) => {
    return addReminder({
      type: REMINDER_TYPES.MATERIAL_MISSING,
      title: '材料缺失提醒',
      message: `案件 ${caseData.caseNumber} 缺少必要材料：${materialData.name}`,
      priority: materialData.required ? PRIORITY_LEVELS.HIGH : PRIORITY_LEVELS.MEDIUM,
      caseId: caseData.id,
      caseNumber: caseData.caseNumber,
      clientName: caseData.clientName,
      targetRole: 'client',
      materialType: materialData.type,
      materialId: materialData.id,
      dueDate: materialData.dueDate,
      actions: [
        {
          type: 'upload',
          label: '上传材料',
          route: `/client/cases/${caseData.id}/materials`
        },
        {
          type: 'contact',
          label: '联系律师',
          route: `/client/cases/${caseData.id}/contact`
        }
      ],
      metadata: {
        materialName: materialData.name,
        materialDescription: materialData.description,
        required: materialData.required
      }
    })
  }

  // 创建截止日期临近提醒
  const createDeadlineReminder = (caseData, daysLeft) => {
    const priority = daysLeft <= 3 ? PRIORITY_LEVELS.URGENT : 
                    daysLeft <= 7 ? PRIORITY_LEVELS.HIGH : PRIORITY_LEVELS.MEDIUM

    return addReminder({
      type: REMINDER_TYPES.DEADLINE_APPROACHING,
      title: '截止日期临近',
      message: `案件 ${caseData.caseNumber} 距离截止日期还有 ${daysLeft} 天`,
      priority: priority,
      caseId: caseData.id,
      caseNumber: caseData.caseNumber,
      clientName: caseData.clientName,
      targetRole: caseData.assignedRole,
      dueDate: caseData.deadline,
      actions: [
        {
          type: 'view',
          label: '查看案件',
          route: `/${caseData.assignedRole}/cases/${caseData.id}`
        }
      ],
      metadata: {
        deadline: caseData.deadline,
        daysLeft: daysLeft
      }
    })
  }

  // 显示/隐藏提醒面板
  const showReminderPanel = () => {
    isReminderVisible.value = true
  }

  const hideReminderPanel = () => {
    isReminderVisible.value = false
  }

  const toggleReminderPanel = () => {
    isReminderVisible.value = !isReminderVisible.value
  }

  // 工具方法
  const generateId = () => {
    return 'reminder_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
  }

  // 初始化模拟数据
  const initMockData = () => {
    // 模拟一些提醒数据
    const mockReminders = [
      {
        type: REMINDER_TYPES.MATERIAL_MISSING,
        title: '身份证明材料缺失',
        message: '案件 CASE202401001 缺少身份证复印件，请尽快上传',
        priority: PRIORITY_LEVELS.HIGH,
        caseId: 'case_001',
        caseNumber: 'CASE202401001',
        clientName: '张三',
        targetRole: 'client',
        materialType: 'identity',
        materialId: 'material_001',
        dueDate: dayjs().add(3, 'day').format('YYYY-MM-DD'),
        actions: [
          {
            type: 'upload',
            label: '上传材料',
            route: '/client/cases/case_001/materials'
          }
        ],
        metadata: {
          materialName: '身份证复印件',
          required: true
        }
      },
      {
        type: REMINDER_TYPES.MATERIAL_INCOMPLETE,
        title: '医疗材料不完整',
        message: '案件 CASE202401002 的医疗材料信息不完整，请补充相关文件',
        priority: PRIORITY_LEVELS.MEDIUM,
        caseId: 'case_002',
        caseNumber: 'CASE202401002',
        clientName: '李四',
        targetRole: 'client',
        materialType: 'medical',
        materialId: 'material_002',
        dueDate: dayjs().add(5, 'day').format('YYYY-MM-DD'),
        actions: [
          {
            type: 'upload',
            label: '补充材料',
            route: '/client/cases/case_002/materials'
          }
        ]
      },
      {
        type: REMINDER_TYPES.DEADLINE_APPROACHING,
        title: '案件截止日期临近',
        message: '案件 CASE202401003 距离截止日期还有 2 天',
        priority: PRIORITY_LEVELS.URGENT,
        caseId: 'case_003',
        caseNumber: 'CASE202401003',
        clientName: '王五',
        targetRole: 'lawyer',
        dueDate: dayjs().add(2, 'day').format('YYYY-MM-DD'),
        actions: [
          {
            type: 'view',
            label: '查看案件',
            route: '/lawyer/cases/case_003'
          }
        ],
        metadata: {
          daysLeft: 2
        }
      }
    ]

    // 添加模拟数据
    mockReminders.forEach(reminderData => {
      addReminder(reminderData)
    })
  }

  return {
    reminders,
    isReminderVisible,
    REMINDER_TYPES,
    PRIORITY_LEVELS,
    activeReminders,
    unreadReminders,
    urgentReminders,
    materialReminders,
    reminderCount,
    unreadCount,
    addReminder,
    addReminders,
    markAsRead,
    markAllAsRead,
    dismissReminder,
    resolveReminder,
    resolveCaseReminders,
    removeReminder,
    cleanupResolvedReminders,
    getRemindersByType,
    getRemindersByCase,
    getRemindersByRole,
    createMaterialMissingReminder,
    createDeadlineReminder,
    showReminderPanel,
    hideReminderPanel,
    toggleReminderPanel,
    initMockData
  }
})

